package com.zhkj.txg.module.order.vm

import android.app.Application
import androidx.lifecycle.MutableLiveData
import com.chad.library.adapter.base.entity.node.BaseNode
import com.google.gson.GsonBuilder
import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName
import com.zhkj.lib.base.BaseViewModel
import com.zhkj.lib.base.UploadResponse
import com.zhkj.lib.http.*
import com.zhkj.txg.module.find.entity.FindPictureEntity
import com.zhkj.txg.module.order.model.OrderManager

class EvaluateViewModel(application: Application) : BaseViewModel(application) {
    private val orderManager = OrderManager()

    val submitEvaluateLiveData = MutableLiveData<HttpResponse<BaseResponse>>()

    var orderId: Long = 0
    val uiEntity = EvaluateUiEntity()

    fun uploadPicture(token: String, orderId: Long, isGroup: Boolean = false) {
        uploadPictureRecursion(0, token, orderId, isGroup)
    }

    private fun uploadPictureRecursion(index: Int, token: String, orderId: Long, isGroup: Boolean = false) {
        // 判断是否需要继续上传
        if (index < uiEntity.products.size && uiEntity.products[index].comment.imageList.isNotEmpty())
            uiEntity.products[index].comment.imageList.let { imageList ->
                val listener = object : SubscribeListener<UploadResponse> {
                    override fun onStart() {
                        submitEvaluateLiveData.postValue(HttpResponse<BaseResponse>().apply {
                            status = HttpResponseStatus.Status.START
                        })
                    }

                    override fun onSuccess(resp: UploadResponse) {
                        uiEntity.products[index].comment.images = resp.data?.url ?: ""
                        uploadPictureRecursion(index + 1, token, orderId, isGroup)
                    }

                    override fun onFailure(throwable: Throwable) {
                        throwable.printStackTrace()
                        submitEvaluateLiveData.postValue(HttpResponse<BaseResponse>().apply {
                            status = HttpResponseStatus.Status.FAILURE
                            val error = ResponseSubscribeListener.handleThrowable(throwable)
                            exception = error
                        })
                    }
                }
                val fileList = mutableListOf<String>()
                imageList.forEach {
                    if (it.itemType == FindPictureEntity.TYPE_PIC && !it.pictureFilePath.isNullOrEmpty())
                        fileList.add(it.pictureFilePath ?: "")
                }
                // 判断是否有图片需要上传
                if (fileList.isNotEmpty()) {
                    val uploadPicture = orderManager.uploadPicture(fileList, listener)
                    dispose.add(uploadPicture)
                } else uploadPictureRecursion(index + 1, token, orderId, isGroup)
            } else {
            val paramsList = mutableListOf<EvaluateUICommentEntity>()
            uiEntity.products.forEach { paramsList.add(it.comment) }
            val comment =
                GsonBuilder().excludeFieldsWithoutExposeAnnotation().create().toJson(paramsList)

            if (!isGroup) submitEvaluate(token, orderId, comment)
            else groupSubmitEvaluate(token, orderId, paramsList)
        }
    }

    private fun submitEvaluate(token: String, orderId: Long, comment: String) {
        val listener = ViewModelSubscribeListener(submitEvaluateLiveData)
        val submitEvaluate = orderManager.submitEvaluate(token, orderId, comment, listener)
        dispose.add(submitEvaluate)
    }

    private fun groupSubmitEvaluate(token: String, orderId: Long, paramsList: MutableList<EvaluateUICommentEntity>) {
        val listener = ViewModelSubscribeListener(submitEvaluateLiveData)
        if (paramsList.size == 0) return
        val item = paramsList.get(0)
        val submitEvaluate = orderManager.groupSubmitEvaluate(token, orderId, item.goodsId, item.goodsRank, item.content, item.images, listener)
        dispose.add(submitEvaluate)
    }
}

data class EvaluateUiEntity(
    val products: MutableList<EvaluateUIGoodsEntity> = mutableListOf()
)


data class EvaluateUIGoodsEntity(
    val image: String = "",
    val goodsName: String = "",
    val specValue: String = "",
    val comment: EvaluateUICommentEntity = EvaluateUICommentEntity(goodsId = 0)
) : BaseNode() {
    // BaseNode自带，需要将comment字段赋值给它，实现UI功能
    override var childNode: MutableList<BaseNode>? = null
}

data class EvaluateUICommentEntity(
    @Expose
    @SerializedName("goods_rank")
    var goodsRank: Int = 1,
    @Expose
    @SerializedName("goods_id")
    val goodsId: Long,
    @Expose
    var content: String = "",
    val imageList: MutableList<FindPictureEntity> = mutableListOf()
) : BaseNode() {
    // BaseNode自带，无需实现
    override val childNode: MutableList<BaseNode>? = null

    // 当前对象在Adapter中位置
    var uiPosition = 0

    // 调用上传接口之后返回的数据保存字段
    @Expose
    var images: String = ""
}

data class EvaluateParamEntity(
    val goods_id: Long,
    val goods_rank: Int,
    val content: String,
    val images: String
)